from flask import Blueprint, request
from flask_restx import Namespace, Resource
from models.profit import Profit
from extensions import db
from utils.auth import token_required
import uuid

api = Namespace('profits', description='利润相关操作')

@api.route('/')
class ProfitList(Resource):
    @token_required
    def get(self):
        """获取所有利润记录"""
        profits = Profit.query.all()
        return {
            'status': 'success',
            'data': [profit.to_dict() for profit in profits]
        }, 200

    @token_required
    def post(self):
        """创建新利润记录"""
        data = request.get_json()
        
        # 检查必填字段
        required_fields = ['store_id', 'amount', 'type', 'date']
        for field in required_fields:
            if field not in data:
                return {
                    'status': 'error',
                    'message': f'缺少必填字段: {field}'
                }, 400
        
        # 创建新利润记录
        new_profit = Profit(
            profit_id=str(uuid.uuid4()),
            store_id=data['store_id'],
            amount=data['amount'],
            type=data['type'],
            date=data['date'],
            description=data.get('description')
        )
        
        db.session.add(new_profit)
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '利润记录创建成功',
            'data': new_profit.to_dict()
        }, 201

@api.route('/<profit_id>')
class ProfitDetail(Resource):
    @token_required
    def get(self, profit_id):
        """获取单个利润记录"""
        profit = Profit.query.get_or_404(profit_id)
        return {
            'status': 'success',
            'data': profit.to_dict()
        }, 200

    @token_required
    def put(self, profit_id):
        """更新利润记录"""
        profit = Profit.query.get_or_404(profit_id)
        data = request.get_json()
        
        # 更新利润记录
        if 'amount' in data:
            profit.amount = data['amount']
        if 'type' in data:
            profit.type = data['type']
        if 'date' in data:
            profit.date = data['date']
        if 'description' in data:
            profit.description = data['description']
        
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '利润记录更新成功',
            'data': profit.to_dict()
        }, 200

    @token_required
    def delete(self, profit_id):
        """删除利润记录"""
        profit = Profit.query.get_or_404(profit_id)
        
        db.session.delete(profit)
        db.session.commit()
        
        return {
            'status': 'success',
            'message': '利润记录删除成功'
        }, 200